package com.baobaotao.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.baobaotao.domain.User;

@Repository//通过注解定义一个Dao
public class UserDao {
	@Autowired//自动注入JdbcTemplate的bean
	private JdbcTemplate jdbcTemplate;
	public int getMatchCount(String userName,String password){
		String sql = "select count(*) from t_user where user_name=? and password=?";
		return jdbcTemplate.queryForObject(sql, new Object[]{userName,password},Integer.class);
	}
	
	public void updateLoginInfo(User user){
		String sql = "update t_user set last_visit=?,last_ip=?,credits=? where user_id=?";
		jdbcTemplate.update(sql,new Object[]{user.getLastVisit(),user.getLastIp(),user.getCredits(),user.getUserId()});
	}
	
	public User findUserByUserName(final String userName){
		String sql = "select * from t_user where user_name=?";
		final User user = new User();
		jdbcTemplate.query(sql, new Object[]{userName},new RowCallbackHandler(){
			public void processRow(ResultSet rs)throws SQLException{
				user.setUserId(rs.getInt("user_id"));
				user.setUserName(userName);
				user.setCredits(rs.getInt("credits"));
			}
		});	
		return user;
	}
}
